﻿using Ideaa.Data.Infrastructure;
using PersistedModels = Ideaa.Data.Models;
using DomainModels = Ideaa.Domain.Models.Idea;
using Ideaa.Data.Repositories;
using Ideaa.Services.Base;
using Ideaa.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Ideaa.Services.Services
{
    public class IdeaService : BaseService, IIdeaService
    {
        private readonly IIdeaRepository ideaRepository;
        private readonly ISuggestionRepository suggestionRepository;

        //public IdeaService(IUnitOfWork unitOfWork)
        //    : base(unitOfWork)
        //{
        //}

        public IdeaService(IUnitOfWork unitOfWork, IIdeaRepository ideaRepository, ISuggestionRepository suggestionRepository)
            : base(unitOfWork)
        {
            this.ideaRepository = ideaRepository;
            this.suggestionRepository = suggestionRepository;
        }

        public int AddIdea(int id, string createdUserId, string title, string content)
        {
            DomainModels.Idea domainModel = new DomainModels.Idea(createdUserId, title, content);
            PersistedModels.Idea persistedModel;
            this.ideaRepository.AddIdea(domainModel, out persistedModel);
            this.unitOfWork.SaveChanges();

            return persistedModel.Id;
        }

        public void AddSuggestion(string createdUserId, string title, string content, int ideaId)
        {
            DomainModels.Idea idea = this.ideaRepository.GetById(ideaId);
            DomainModels.Suggestion suggestion = idea.AddSuggestion(createdUserId, title, content);
            this.suggestionRepository.AddSuggestion(suggestion);
            this.unitOfWork.SaveChanges();
        }

        public void Add(PersistedModels.Idea idea)
        {
            if (idea != null)
            {
                this.unitOfWork.Ideas.Add(idea);
                this.unitOfWork.SaveChanges();
            }
            else
            {
                throw new NullReferenceException("Cannot add entity. Entity is null.");
            }
        }

        public IList<PersistedModels.Idea> GetAll()
        {
            return this.unitOfWork.Ideas.All().ToList();
        }


        public IList<PersistedModels.Idea> SearchIdeas(string searchString)
        {



            return new List<PersistedModels.Idea>();
        }


        public PersistedModels.Idea GetIdeaById(int ideaId)
        {
            if (ideaId < 1)
            {
                throw new Exception("Idea could not be found");
            }
            return this.unitOfWork.Ideas.GetById(ideaId);
        }
    }
}
